import cn.hutool.core.lang.tree.TreeNodeConfig;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 * User: chen
 * Date: 2024/1/9
 */
public class ListUtil {

    /**
     * 递归查询子节点
     *
     * @param root 根节点
     * @param all  所有节点
     * @return 根节点信息
     */
    private static List<Menu> getChildrens(Menu root, List<Menu> all) {

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();

        List<Menu> children = all.stream().filter(m -> {
            return Objects.equals(m.getParentId(), root.getId());
        }).map((m) -> {
                    m.setChildList(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }


    public static List<Menu> getFilePathTree(List<String> paths) {
        Map<String, Integer> map = new LinkedHashMap<>();
        Integer id = 1;
        for (int i = 0; i < paths.size(); i++) {
            String[] path = paths.get(i).split("/");
            String p = "";
            for (int j = 0; j < path.length; j++) {
                p += path[j] + "/";
                if (!map.containsKey(p.substring(0, p.length() - 1))) {
                    map.put(p.substring(0, p.length() - 1), id++);
                }
            }
        }

        List<Menu> menus = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            Menu menu = new Menu();
            Integer values = entry.getValue();
            String[] keys = entry.getKey().split("/");
            menu.setId(values);
            if (keys.length == 1) {
                menu.setParentId(0);
                menu.setName(keys[0]);
                menu.setPath(keys[0]);
            } else {
                String path = "";
                for (int i = 0; i < keys.length - 1; i++) {
                    path += keys[i] + "/";
                }
                menu.setName(keys[keys.length - 1]);
                menu.setPath(String.join("/", keys));
                path = path.substring(0, path.length() - 1);
                menu.setParentId(map.get(path));
            }
            menus.add(menu);
        }
        //获取父节点
        List<Menu> collect = menus.stream().filter(m -> m.getParentId() == 0).map(
                (m) -> {
                    m.setChildList(getChildrens(m, menus));
                    return m;
                }
        ).collect(Collectors.toList());

        return collect;
    }


}
